package demo.sort;

import com.alibaba.fastjson.JSON;

/**
 * @Author: admin
 * @Description:
 * @Date: Create in 2021/6/6-15:48
 */
public class QuickSort {

    public static void main(String[] args) {
        int[] arr = new int[]{7, 3,2,10,8,1, 9, 5,4,6,6};
        quickSort(arr,0,arr.length-1);
        System.out.println(JSON.toJSONString(arr));
    }

    static void swap(int[] arr, int i, int pos) {
        int temp = arr[i];
        arr[i] = arr[pos];
        arr[pos] = temp;
    }

    public static void quickSort(int[] arr, int left, int right) {
        if(left>=right){
            return;
        }
        int mid = sort(arr, left, right);
//        System.out.println(JSON.toJSONString(arr)+"  mid->"+mid+" left->"+left+"right->"+right);
        quickSort(arr, left, mid-1);
        quickSort(arr, mid+1, right);


    }

    public static int sort(int[] arr, int left, int right) {
        int baseArr = arr[right];
        int l=left,r=right-1;

        while(l<r){
            while (l<=r&&arr[l]<=baseArr){
                l++;
            }
            while (l<=r&&arr[r]>baseArr){
                r--;
            }
           if(l<r){
//               System.out.println("l->"+l+";r->r");
               swap(arr,l,r);
           }
        }
//        System.out.println(l);
        if(arr[l]>arr[right]){
            swap(arr,l,right);
        }


        return l;
//        sort(arr, left, mid);
//        sort(arr, mid+1, right);

    }

    ;


    static void merge(int[] arr, int leftPtr, int rightPtr, int rightBound) {
        int[] temp = new int[rightBound - leftPtr + 1];
        int mid = rightPtr - 1;
        int i = leftPtr;
        int j = rightPtr;
        int k = 0;
        while (i <= mid && j <= rightBound) {
            temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
        }
        while (i <= mid) {
            temp[k++] = arr[i++];
        }
        while (j <= rightBound) {
            temp[k++] = arr[j++];
        }
        System.arraycopy(temp, 0, arr, leftPtr, temp.length);

    }

}
